package arrAndstr;

import java.util.*;

/*
    155. 最小栈
    我们可以在每个元素 a 入栈时把当前栈的最小值 m 存储起来。
 */
public class T155 {
    class MinStack {

        private Stack<Integer> stack;
        private TreeMap<Integer, Integer> map;  // (num, count)

        public MinStack() {
            this.stack = new Stack<>();
            this.map = new TreeMap<>();
        }

        public void push(int val) {
            this.stack.push(val);
            if (this.map.containsKey(val)) {
                this.map.put(val, this.map.get(val)+1);
            } else {
                this.map.put(val, 1);
            }
        }

        public void pop() {
            int val = this.stack.pop();
            if (this.map.get(val) != 1) {
                this.map.put(val, this.map.get(val)-1);
            } else {
                this.map.remove(val);
            }
        }

        public int top() {
            return this.stack.peek();
        }

        public int getMin() {
            for(Map.Entry<Integer, Integer> entry : this.map.entrySet()) {
                return entry.getKey();
            }
            return -1;
        }
    }

/**
 * Your MinStack object will be instantiated and called as such:
 * MinStack obj = new MinStack();
 * obj.push(val);
 * obj.pop();
 * int param_3 = obj.top();
 * int param_4 = obj.getMin();
 */
}
